﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PTA.Db;
namespace PTA.TreeHelper
{
    public class SqlTreeDal<N> : CommonTreeDal<N>
        where N : BaseTreeNode, new()
    {
        private string table = string.Empty;
        private SqlDataAccess db = null;

        public SqlTreeDal(SqlDataAccess db)
            : base(db)
        {
            this.db = db;
            if (Reflect.HasAttribute<TableAttribute>(typeof(N)))
            {
                table = Reflect.GetAttribute<TableAttribute>(typeof(N)).Name;
            }
            else
            {
                table = typeof(N).Name;
            }
        }

        public override N Add(N node)
        {
            using (System.Transactions.TransactionScope trans = new System.Transactions.TransactionScope())
            {
                var sqlcmd = new SqlDataCommand("InsertTreeNode");
                sqlcmd.AddIn("TableName", table);
                sqlcmd.AddIn("NodeName", node.NodeName);
                sqlcmd.AddIn("ParentId", node.ParentId);
                sqlcmd.AddIn("OwnerId", node.OwnerId);
                sqlcmd.AddOut("NodeId", System.Data.SqlDbType.Int);
                var x = db.ExecuteNonQuery(sqlcmd);

                node.NodeId = PTA.Convert.ToInt32(x.Parameters["@NodeId"].Value);
                db.Update(node);
                return node;
            }
        }

        public override void Delete(int nid)
        {
            var sqlcmd = new SqlDataCommand("DeleteTreeNode");
            sqlcmd.AddIn("TableName", table);
            sqlcmd.AddIn("NodeId", nid);
            db.ExecuteNonQuery(sqlcmd);
        }

        public override void Move(int nid, MoveDirection direction)
        {
            var sqlcmd = new SqlDataCommand("MoveTreeNode");
            sqlcmd.AddIn("TableName", table);
            sqlcmd.AddIn("NodeId", nid);
            sqlcmd.AddIn("Direction", (byte)(int)direction);
            db.ExecuteNonQuery(sqlcmd);

        }
    }
}
